package com.rfy.framework.util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @author: zhang
 * @date: 2018-12-24 20:07
 * @description：MD5工具
 */
public class MD5Util {


	private static final String ALGORITHM = "MD5";
	private static final int LENGTH = 16;
	private static final int CHAR_LENGTH = 32;
	private static final int FOUR_BIT=4;

	/**
	 * md5摘要运算
	 * @param s
	 * @return
	 */
	public static String getMD5Encoding(String s) {
		byte[] input = s.getBytes();
		String output = null;
		// 声明16进制字母
		char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'A', 'B', 'C', 'D', 'E', 'F' };
		try {
			// 获得一个MD5摘要算法的对象
			MessageDigest md = MessageDigest.getInstance(ALGORITHM);
			md.update(input);

			// 获得MD5的摘要结果
			byte[] tmp = md.digest();
			char[] str = new char[CHAR_LENGTH];
			byte b = 0;
			for (int i = 0; i < LENGTH; i++) {
				b = tmp[i];

				// 取每一个字节的低四位换成16进制字母
				str[2 * i] = hexChar[b >>> FOUR_BIT & 0xf];

				// 取每一个字节的高四位换成16进制字母
				str[2 * i + 1] = hexChar[b & 0xf];
			}
			output = new String(str);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return output;
	}

	/**
	 * md5计算摘要并base64编码
	 * @param param
	 * @return
	 */
	public static String getMD5AndBase64(String param) {
		MessageDigest digest = null;
		String result = null;
		if (param == null) {
			return null;
		}
		try {
			digest = MessageDigest.getInstance(ALGORITHM);
			result = Base64.getEncoder().encodeToString(digest.digest(param.getBytes(StandardCharsets.UTF_8)));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return result;

	}

}
